from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.shortcuts import render
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.authentication import JWTAuthentication

from app.users.models import VerifyCode
from app.users.serializers import VerifyCodeSerializer, RegisterSerializer, UserDetailSerializer

User = get_user_model()


# Create your views here.
class MyModelBackend(ModelBackend):
    # 重写认证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) |
                                    Q(phone=username))
        except Exception as e:
            return None
        else:
            if user.check_password(password):
                return user


class VerifyView(GenericViewSet, CreateModelMixin):
    '''
    create:
    发送验证码
    '''
    serializer_class = VerifyCodeSerializer

    def perform_create(self, serializer):
        email = serializer.data['email']
        # 生成验证码
        from utils.code import generate_code
        code = generate_code()
        from utils.send_verifyCode import Mail
        # 实例化邮件对象
        mail = Mail(message=code, recipient=email)
        try:
            result = mail.send()
        except Exception as e:
            return '验证码发送失败'
        else:
            if result == 1:
                # 实例化验证码对象
                verifycode = VerifyCode()
                verifycode.email = email
                verifycode.code = code
                verifycode.save()
                return '验证码发送成功'
            else:
                return '验证码发送失败'

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        result = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(dict(message=result))


class RegisterView(GenericViewSet, CreateModelMixin):
    '''
    create:
    注册
    '''
    serializer_class = RegisterSerializer


class UserView(GenericViewSet, RetrieveModelMixin, UpdateModelMixin):
    queryset = User.objects.all()
    # 认证管理
    authentication_classes = [JWTAuthentication,SessionAuthentication]
    # 权限认证
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = UserDetailSerializer

    # 限制查看信息时只能查看当前对象
    def get_object(self):
        return self.request.user
